package filter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.JdbcUtil;
import util.Log;
public class ConfigFilter implements Filter{
	Connection conn = null;
	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest  req = (HttpServletRequest)request;
		HttpServletResponse  res = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		
		System.out.println("开始检测语言"+session.getAttribute("username"));
		
		//如果已经保存了用户登录
		if(session.getAttribute("username") != null && 
				session.getAttribute("language_code")!=null && session.getAttribute("language_code")!="" )
		{
			if(session.getAttribute("bundle") == null){
				ResourceBundle bundle = ResourceBundle.getBundle("app",new Locale((String) session.getAttribute("language_code")));
				session.setAttribute("bundle", bundle);
			}
//			if(req.getParameter("request_locale") == null)
//				res.sendRedirect("index.action?request_locale="+session.getAttribute("language_code"));
				
		}
		else if(null != session.getAttribute("username")){
			PreparedStatement stm = null;
			String sql = "select language_code from gt_member where user_name=?";
			try {
				stm = conn.prepareStatement(sql);
				stm.setString(1, (String) session.getAttribute("username"));
				ResultSet set = stm.executeQuery();
				
				//从数据库中加载该配置信息：language_code,并保存在session中
				if(set.next()){
					session.setAttribute("language_code", set.getString(1));
					System.out.println("设置用户编码为数据库:"+session.getAttribute("language_code"));
					
					if(session.getAttribute("bundle") == null){
					ResourceBundle bundle = ResourceBundle.getBundle("app",new Locale(set.getString(1)));
					session.setAttribute("bundle", bundle);
					}
					
//					if(req.getParameter("request_locale") == null)
//						res.sendRedirect("index.action?request_locale="+set.getString(1));
				}
				else{//如果未找到该用户,说明这是一个logic error
					Log.err2DB("未在数据库找到用户："+session.getAttribute("username"), null, "logic error", req);
				}
				
			} catch (SQLException e) {
				Log.err2DB("执行sql语句出错："+sql, e, Log.SQL_ERROR, req);
				e.printStackTrace();
			}
		}
		
		chain.doFilter(req, res);
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		
		conn = JdbcUtil.getConnection("decuries");
	}
	
}
